package com.hongshu.file.service.impl;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.hongshu.common.core.domain.R;
import com.hongshu.common.core.enums.OssProviderEnum;
import com.hongshu.file.domain.OssConfigDTO;
import com.hongshu.file.service.ISysFileService;
import com.hongshu.file.utils.FileUploadUtils;
import com.hongshu.system.api.RemoteWebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Map;

/**
 * 本地文件存储
 *
 * @author hongshu
 */
@Service
public class LocalSysFileServiceImpl implements ISysFileService {

    @Autowired
    private RemoteWebService remoteWebService;


    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        R<?> r = remoteWebService.getOssConfig();
        Object data = r.getData();
        Map<String, OssConfigDTO> ossMap =
                JSONUtil.toBean(JSONUtil.parseObj(data),
                        new TypeReference<Map<String, OssConfigDTO>>() {
                        }, false);
        OssConfigDTO ossConfig = ossMap.get(OssProviderEnum.LOCAL.getCode());

        String name = FileUploadUtils.upload(ossConfig.getUrl(), file);
        String localFilePrefix = "/profile"; // 与 ResourcesConfig 保持一致
        return ossConfig.getDomain() + localFilePrefix + name;
    }

    @Override
    public String uploadFile(File file) {
        return null;
    }
}
